<template>
  <el-card>
    <el-form :inline="true" class="form">
      <el-form-item label="用户名:">
        <el-input
          placeholder="请你输入搜索的用户名"
          v-model="keyword"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="handleSearch"
          :disabled="keyword ? false : true"
        >
          搜索
        </el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card style="margin: 10px 0px">
    <el-button type="primary" @click="addUser">添加用户</el-button>
    <el-button
      type="danger"
      :disabled="selectIdArr.length > 0 ? false : true"
      @click="deleteSelectUser"
    >
      批量删除
    </el-button>
    <!-- 表格展示用户信息 -->
    <el-table
      @selection-change="selectChange"
      :data="userArr"
      style="margin: 10px 0px"
      border
    >
      <el-table-column align="center" type="selection"></el-table-column>
      <el-table-column
        type="index"
        label="序号"
        width="80px"
        align="center"
      ></el-table-column>
      <el-table-column prop="id" label="ID" align="center"></el-table-column>
      <el-table-column
        prop="username"
        label="用户名字"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="name"
        label="用户名称"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="roleName"
        label="用户角色"
        align="center"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间"
        align="center"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column
        prop="updateTime"
        label="更新时间"
        align="center"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column width="300px" label="操作" align="center">
        <template #="{ row, $index }">
          <el-button
            @click="setRole(row)"
            type="primary"
            plain
            icon="User"
            size="small"
          >
            分配角色
          </el-button>
          <el-button
            @click="updareUser(row)"
            type="success"
            plain
            icon="Edit"
            size="small"
          >
            编辑
          </el-button>
          <el-popconfirm
            :title="`你确定要删除${row.username}吗?`"
            width="250px"
            @confirm="deleteUser(row.id)"
          >
            <template #reference>
              <el-button type="danger" plain icon="Delete" size="small">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      @current-change="getUserInfo"
      @size-change="handler"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :background="true"
      :page-sizes="[5, 7, 9, 11]"
      :total="total"
      layout="prev,pager,next,jumper,->,sizes,total"
    ></el-pagination>
    <!-- 抽屉效果 -->
    <el-drawer v-model="drawer">
      <template #header>
        <h4>{{ userParams.id ? '更新用户' : '添加用户' }}</h4>
      </template>
      <template #default>
        <el-form ref="formRef" :model="userParams" :rules="rules">
          <el-form-item label="用户姓名" prop="username">
            <el-input
              v-model="userParams.username"
              placeholder="请输入用户姓名"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="name">
            <el-input
              v-model="userParams.name"
              placeholder="请输入用户昵称"
            ></el-input>
          </el-form-item>
          <el-form-item v-if="!userParams.id" label="用户密码" prop="password">
            <el-input
              v-model="userParams.password"
              placeholder="请输入用户密码"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 抽屉 分配角色 -->
    <el-drawer v-model="drawer1">
      <template #header>
        <h4>分配角色(职位)</h4>
      </template>
      <template #default>
        <el-form>
          <el-form-item label="用户姓名">
            <el-input :disabled="true" v-model="userParams.username"></el-input>
          </el-form-item>
          <el-form-item label="角色列表">
            <el-checkbox
              style="width: 100%"
              @change="handleCheckAllChange"
              v-model="checkAll"
              :indeterminate="indeterminate"
            >
              全选
            </el-checkbox>
            <el-checkbox-group
              @change="handleCheckedRoleChange"
              v-model="userRole"
            >
              <el-checkbox
                v-for="role in allRoles"
                :key="role"
                :label="role.roleName"
                :value="role"
              >
                {{ role.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button @click="drawer1 = false">取消</el-button>
          <el-button type="primary" @click="confirmClick">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, nextTick } from 'vue'
import {
  reqSetUserRole,
  reqUserInfo,
  reqAddOrUpdateUser,
  reqAllRole,
  reqRemoveUser,
  reqSelectUser,
} from '@/api/acl/user'
import {
  UserResponseData,
  User,
  Records,
  AllRoleResponseData,
  AllRole,
  SetRoleData,
} from '@/api/acl/user/type'
import { ElMessage } from 'element-plus'
import useUserStore from '@/store/modules/user'
import useLayoutSettingStore from '@/store/modules/setting'
let currentPage = ref<number>(1)
let pageSize = ref<number>(5)
let userArr = ref<Records>([])
let total = ref<number>(0)
let checkAll = ref<boolean>(false)
let indeterminate = ref<boolean>(true)
let userRole = ref<AllRole>([])
let allRoles = ref<AllRole>([])
// 获取form组件实例
let formRef = ref()
const userStore = useUserStore()
// 收集用户信息的数据
let userParams = reactive<User>({
  username: '',
  name: '',
  password: '',
})
// 控制抽屉显示与隐藏
let drawer = ref<boolean>(false)
// 控制分配角色抽屉显示与隐藏
let drawer1 = ref<boolean>(false)
// 准备一个数组存储批量删除的用户
let selectIdArr = ref<number[]>([])
// 定义响应式数据收集用户输入的关键字
let keyword = ref<string>('')
onMounted(() => {
  getUserInfo()
})
// 获取仓库
const layoutSettingStore = useLayoutSettingStore()
const getUserInfo = async (pager = 1) => {
  currentPage.value = pager
  const result: UserResponseData = await reqUserInfo(
    currentPage.value,
    pageSize.value,
    keyword.value,
  )
  if (result.code == 200) {
    userArr.value = result.data.records
    total.value = result.data.total
  } else {
    ElMessage({
      type: 'error',
      message: '获取用户信息失败',
    })
  }
}
// 分页器下拉菜单回调
const handler = () => {
  getUserInfo()
}
// 添加用户按钮
const addUser = () => {
  drawer.value = true
  // 清空数据
  Object.assign(userParams, {
    id: 0,
    username: '',
    name: '',
    password: '',
  })
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })
}
// 更新用户的按钮
const updareUser = (row: User) => {
  drawer.value = true
  Object.assign(userParams, row)
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
  })
}
// 添加/更新用户的回调
const save = async () => {
  // 点击保存时，务必先保证表单校验通过再发请求
  await formRef.value.validate()
  const result: any = await reqAddOrUpdateUser(userParams)
  if (result.code == 200) {
    drawer.value = false
    ElMessage({
      type: 'success',
      message: userParams.id ? '更新用户成功' : '添加用户成功',
    })
    getUserInfo(userParams.id ? currentPage.value : 1)
    // 浏览器自动刷新一次 以保证用户信息发生变化后重新进行登录
    if (userParams.id && userStore.username == userParams.username) {
      window.location.reload()
    }
  } else {
    drawer.value = false
    ElMessage({
      type: 'error',
      message: userParams.id ? '更新用户失败' : '添加用户失败',
    })
  }
}
// 关闭按钮的回调
const cancel = () => {
  drawer.value = false
}
// 校验用户名字的回调函数
const validatorUsername = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户名字至少五位'))
  }
}
const validatorName = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户昵称至少五位'))
  }
}
const validatorPassword = (rule: any, value: any, callback: any) => {
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户密码至少六位'))
  }
}
// 表单校验规则
const rules = {
  // 用户名称
  username: [
    {
      required: true,
      trigger: 'blur',
      validator: validatorUsername,
    },
  ],
  // 用户昵称
  name: [
    {
      required: true,
      trigger: 'blur',
      validator: validatorName,
    },
  ],
  // 用户密码
  password: [
    {
      required: true,
      trigger: 'blur',
      validator: validatorPassword,
    },
  ],
}
// 分配角色按钮的回调
const setRole = async (row: User) => {
  Object.assign(userParams, row)
  // 获取全部职位数据与当前用户已有的职位
  const result: AllRoleResponseData = await reqAllRole(userParams.id as number)
  if (result.code == 200) {
    // 存储全部职位
    allRoles.value = result.data.allRolesList
    // 存储当前用户已有的职位
    userRole.value = result.data.assignRoles
    drawer1.value = true
  }
  if (userRole.value.length > 0) {
    indeterminate.value = true
  } else {
    indeterminate.value = false
  }
}
// 全选复选框的change事件
const handleCheckAllChange = (val: boolean) => {
  userRole.value = val ? allRoles.value : []
  indeterminate.value = false
}
// 底部复选框change事件
const handleCheckedRoleChange = (val: string[]) => {
  const checkedCount = val.length
  checkAll.value = checkedCount === allRoles.value.length
  indeterminate.value = checkedCount > 0 && checkedCount < allRoles.value.length
}
// 确定按钮的回调
const confirmClick = async () => {
  let data: SetRoleData = {
    userId: userParams.id as number,
    roleIdList: userRole.value.map((item) => item.id) as number[],
  }
  const result = await reqSetUserRole(data)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '分配角色成功',
    })
    drawer1.value = false
    getUserInfo(currentPage.value)
  } else {
    ElMessage({
      type: 'error',
      message: '分配角色失败',
    })
    drawer1.value = false
  }
}
// 删除某个用户
const deleteUser = async (id: number) => {
  const result: any = await reqRemoveUser(id)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getUserInfo(
      userArr.value.length > 0 ? currentPage.value : currentPage.value - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}
// table复选框勾选时触发事件
const selectChange = (val: any) => {
  selectIdArr.value = val.map((item: any) => item.id as number)
}
// 批量删除按钮的回调
const deleteSelectUser = async () => {
  const result = await reqSelectUser(selectIdArr.value)
  if (result.code == 200) {
    ElMessage({
      type: 'success',
      message: '批量删除成功',
    })
    getUserInfo(
      userArr.value.length > 0 ? currentPage.value : currentPage.value - 1,
    )
  } else {
    ElMessage({
      type: 'error',
      message: '批量删除失败',
    })
  }
}
// 搜索按钮的回调
const handleSearch = () => {
  getUserInfo()
}
// 重置按钮的回调
const reset = () => {
  layoutSettingStore.changeRefresh()
}
</script>

<style scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>